package com.qubi.exchange.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.extern.log4j.Log4j2;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author wx
 * @create 2019-02-13 10:50
 **/
@Data
@Table(name = "t_me_balance")
@Log4j2
public class Balance {
    @Id
    @JSONField(serialize = false)

    String id;
    @Column(name = "user_id")
    @JSONField(serialize = false)
    String userId;
    @Column(name = "coin_code")
    String coinCode;
    @Column(name = "balance_available")
    BigDecimal balanceAvailable;
    @Column(name = "balance_frozen")
    BigDecimal balanceFrozen;
    @Column(name = "locks")
    BigDecimal locks;


    public BigDecimal getLocks()
    {
        if(locks==null) return BigDecimal.ZERO;

        return locks;

    }
    @Transient
    BigDecimal worth;


    @JSONField(serialize = false)
    public Balance getSelf() {
        return this;
    }
    @JSONField(serialize = false)
    @Transient
    AtomicBoolean onChange=new AtomicBoolean(false);


    public boolean changeBalance(final BigDecimal available, final BigDecimal frozen,final BigDecimal  lock)
    {
        boolean result=true;

        while(true){
            if(onChange.compareAndExchange(false,true)){

                if(available!=null){
                    var newAvailable=this.balanceAvailable.add(available);
                    if(newAvailable.compareTo(BigDecimal.ZERO)<0) result=false;
                    else this.balanceAvailable=newAvailable;
                }
                if(frozen!=null&&result){
                    var newFrozen=this.balanceFrozen.add(frozen);
                    if(newFrozen.compareTo(BigDecimal.ZERO)<0) result=false;
                    else this.balanceFrozen=newFrozen;
                }
                if(lock!=null&&result){
                    var newLock=this.locks.add(lock);
                    if(newLock.compareTo(BigDecimal.ZERO)<0) result=false;
                    else this.locks=newLock;
                }
                log.info("用户uid: {} ,{} 币币资产改变,可用增加 {} 冻结增加: {}",userId,coinCode,available.toString(),frozen.toString());
                onChange.set(false);
                break;
            }
        }
        return result;

    }
}
